using UnityEngine;
using System.Collections;

public class EntityMgr {
	private int worldLayer 		= 0;
	private int buildLayer 		= 8;
	private int inventoryLayer 	= 10;
	
	private Inventory inventory = new Inventory();
	private Transform buildScreenContainer;
	
	// ItemMgr constructor.
	public EntityMgr(Transform buildScreenContainer) {
		this.buildScreenContainer = buildScreenContainer;
	}
	
	// Returns true if the inventory contains atleast one item.
	public bool hasItem() {
		return inventory.count() > 0;	
	}
	
	// Drops the selected item in the inventory into the world
	// at the specified position.
	public GameObject toWorld(Vector3 position) {
		Entity entity = inventory.pop();
		
		// Make sure the inventory is not empty.
		if (entity != null) {
			entity.transform.position = position;
			entity.transform.parent   = null;
			
			entity.each(delegate(GameObject obj) {
				obj.layer = worldLayer;
				return false;
			});
			
			return entity.gameObject;
			
		} else {
			Debug.Log("Attempting to drop an item from an empty inventory.");
			return null;
		}
	}
	
	// Takes an entity from the world and puts it into
	// the inventory. All layer switching and parent
	// change will be handled. If the object has other
	// components attached to it, they will also be
	// moved.
	public void fromWorld(Entity entity) {
		entity.transform.position 	= Vector3.zero;
		entity.transform.parent 	= null;
		
		entity.each(delegate(GameObject o) {
			o.layer = inventoryLayer;
			return false;
		});
		
		inventory.push(entity);
	}
	
	// Moves the selected item from the inventory into
	// the Build Screen.
	public Entity toBuildScreen(Vector3 position) {
		Entity entity = inventory.pop();
		
		if (entity != null) {
			entity.transform.position 	= position;
			entity.transform.parent 	= buildScreenContainer;
			
			entity.each(delegate(GameObject o) {
				o.layer = buildLayer;
				return false;
			});
			
			return entity;
		} else {
			return null;
		}
	}
	
	// Takes an item from the Build Screen and puts it
	// into the inventory. If the entity has other components
	// attached to it, they will be included.
	public void fromBuildScreen(Entity entity) {
		entity.transform.parent = null;
		
		entity.each(delegate(GameObject o) {
			o.layer = inventoryLayer;
			return false;
		});
		
		inventory.push(entity);
	}
	
	// Shifts the selection left or right. Use the public enum 
	// Inventory.Direction to choose direction. This function 
	// makes sure the selection does not go out of bounds. If 
	// the number of entities is 0, the selection will be 0 but the 
	// peek() function will return null.
	public void shift(Inventory.Direction dir) {
		inventory.shift(dir);
	}
	
	// Returns the selected item without removing it.
	// 
	public Entity peek() {
		return inventory.peek();
	}
}
